package com.chcit.mobile.mvp.inventory.presenter;

import android.app.Application;

import com.alibaba.fastjson.JSONObject;
import com.chcit.mobile.app.exception.BaseException;
import com.chcit.mobile.common.SPDErrorHandle;
import com.chcit.mobile.mvp.entity.ResultBean;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

import javax.inject.Inject;

import com.chcit.mobile.mvp.inventory.contract.MovementPlanDetailContract;
import com.jess.arms.utils.RxLifecycleUtils;

@FragmentScope
public class MovementPlanDetailPresenter extends BasePresenter<MovementPlanDetailContract.Model, MovementPlanDetailContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    public boolean isError = false;

    @Inject
    public MovementPlanDetailPresenter(MovementPlanDetailContract.Model model, MovementPlanDetailContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    /**
     *  移库确认
     * @param paramReq
     * @param action
     */
    public void movePlanConform(JSONObject paramReq, Action action) {
        mModel.movePlanSubmit(paramReq)
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .doFinally(() -> {
                    mRootView.hideLoading();
                }).subscribe(new SPDErrorHandle<ResultBean>(mErrorHandler) {
            @Override
            public void onNext(ResultBean resultBean) {
                try {
                    if(resultBean.isSuccess()){
                        action.run();
                    }else{
                        String msg = resultBean.getMsg();
                        if(msg.isEmpty()){
                            msg = "未知错误！";
                        }
                        throw new BaseException(msg);
                    }
                } catch (Exception e) {
                    onError(e);
                }
            }

            @Override
            public void onError(Throwable t) {
                isError = true;
                super.onError(t);
            }
        });
    }
}
